package com.xiaoran.client.zk;

import com.google.common.collect.Lists;
import com.xiaoran.client.cache.ServiceRouteCache;
import com.xiaoran.client.channel.ProviderService;
import com.xiaoran.client.config.ClientValue;
import com.xiaoran.common.utils.IpUtil;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class ZKit {
    @Autowired
    private ClientValue clientValue;
    @Autowired
    private ZkClient zkClient;
    @Autowired
    private ServiceRouteCache serviceRouteCache;


    public List<ProviderService> getServiceInfos(String serviceName) {
        String path=clientValue.getZkRoot()+"/"+serviceName;
        List<String> children = zkClient.getChildren(path);
        return convertToProviderService(children);
    }

    private List<ProviderService> convertToProviderService(List<String> children) {
        if (CollectionUtils.isEmpty(children)){
            return Lists.newArrayListWithCapacity(0);
        }

        return children.stream().map(item -> {
            String[] split = item.split(":");
            String ipAddress = split[0];
            String serverPort = split[1];
            String networkPort = split[2];
            return ProviderService.builder()
                    .serverPort(Integer.parseInt(serverPort))
                    .networkPort(Integer.parseInt(networkPort))
                    .serverIp(ipAddress)
                    .build();
        }).collect(Collectors.toList());
    }

    public void subscribeZKEvent(String serviceName) {
        String path=clientValue.getZkRoot()+"/"+serviceName;
        zkClient.subscribeChildChanges(path, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> list) throws Exception {
                if (!CollectionUtils.isEmpty(list)){
                    List<ProviderService> providerServices = convertToProviderService(list);
                    serviceRouteCache.updateCache(serviceName,providerServices);
                }
            }
        });
    }
}
